package com.i2works.smartluolong.utils.common;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @author koal <koal@vip.qq.com>
 * @date 2017/4/5 17:14
 */
@Component
public class ConfigUtil {

    //重新读取配置文件的延时时间：三分钟
    private static final long DELAY_MILLIS = 20 * 1000;
    private static final String WEB_PROPERTIES_URL = ResourceUtils.CLASSPATH_URL_PREFIX + "application.properties";
    /**
     * 获取file
     */
    private static File getFiles(String url) {
        //从这个文件读取数据
        URL resource;
        if (StringUtils.isNotBlank(url)) {
            resource = Thread.currentThread().getContextClassLoader().getResource(url);
        } else {
            resource = Thread.currentThread().getContextClassLoader().getResource(WEB_PROPERTIES_URL);
        }
        File propertiesFile = null;
        if (resource != null) {
            propertiesFile = new File(resource.getPath());
        }
        return propertiesFile;
    }

    /**
     * 获取配置根据KEY获取值
     */
    public static String get(String key) {
        String value = null;
        try {
            if (StringUtils.isNotBlank(key)) {
                PropertiesConfiguration configuration = ConfigUtil.init(WEB_PROPERTIES_URL);
                if (configuration != null) {
                    value = configuration.getString(key);
                }
            }
        } catch (Exception e) {
            System.err.println("ConfigUtil.get(java.lang.String)异常：" + e);
        }
        return value;
    }

    /**
     * 获取配置根据KEY获取值（泛型）
     */
    public static <T> T get(String key, Class<T> clazz) {
        T value = null;
        try {
            value = clazz.newInstance();
            if (StringUtils.isNotBlank(key)) {
                PropertiesConfiguration configuration = ConfigUtil.init(WEB_PROPERTIES_URL);
                if (configuration != null) {
                    value = configuration.get(clazz, key);
                }
            }
        } catch (Exception e) {
            System.err.println("ConfigUtil.get(java.lang.String, java.lang.Class<T>)异常：" + e);
        }
        return value;
    }


    /**
     * 返回配置
     */
    public static PropertiesConfiguration init(String url) throws Exception {
        File propertiesFile = getFiles(url);
        if (propertiesFile.exists()) {
            //加载文件
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class);
            //获取配置
            builder.configure(new Parameters().fileBased().setFile(propertiesFile));
            //返回数据
            return builder.getConfiguration();
        }
        return null;
    }

    /**
     * 返回配置(热部署)
     */
    @Deprecated
    public static PropertiesConfiguration reloadInit(String url) throws Exception {
        File propertiesFile = getFiles(url);
        if (propertiesFile.exists()) {
            //热部署
            ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder = new ReloadingFileBasedConfigurationBuilder<>(PropertiesConfiguration.class);
            //参数配置
            builder.configure(new Parameters().fileBased().setFile(propertiesFile).setReloadingRefreshDelay(DELAY_MILLIS));
            //热部署时间
            PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(), null, 1, TimeUnit.MINUTES);
            trigger.start();
            return builder.getConfiguration();
        }
        return null;
    }


}
